<?php

namespace App\Http\Middleware;

use App\Http\Controllers\ExpressController;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Predis\Client;

class AccessTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    const excepted_url = ['api/token', 'api/login'];

    public function handle(Request $request, Closure $next)
    {
        if (in_array($request->path(), self::excepted_url)) {
            return $next($request);
        }
        $token = $request->hasHeader("MZToken");
        if (empty($token)) {
            return response()->json([
                'success' => false,
                'code' => -1,
                'msg' => "No Token"
            ], 500);
        } else {
            $token = $request->header("MZToken");
            $val = Redis::get(ExpressController::LOGIN_PREFIX . $token);
            if (empty($val)) {
                return response()->json([
                    'success' => false,
                    'code' => -1,
                    'msg' => "Error Token",
                    'data' => null
                ], 500);
            }
        }
        $request["userid"] = dectypt_id($token, env('TOKEN_ENCRYPT_KEY'));
        return $next($request);
    }
}
